package com.sensetime.bi.senselink.server.rtsptest;

import java.io.IOException;
import java.util.StringTokenizer;

public class RtspResponseParse {
    // Goes through the received string from the server
    // Also allows us to parse through and see if there is track
    // information and the type of transport this server supports
    public static int parseServerResponse(RtspCtl ctl) {
        System.out.println("================= recv =================");
        int replyCode = 0;

        try {
            // Read first line - Status line.  If all goes well
            // this should give us: RTSP/1.0 200 OK
//            boolean ready = ctl.RTSPBufferedReader.ready();
//            if (ready) {
//                System.out.println("is redeay to read");
//            }

            String statusLine = ctl.RTSPBufferedReader.readLine();
            System.out.println("================= recv finish =================");

            if (statusLine == null) {
                System.out.println("Could not communiate with server");
                return -1;
            }

            System.out.println(statusLine);

            // Tokenize the string and grab the next token, which is
            // the status code
            StringTokenizer tokens = new StringTokenizer(statusLine, " \t\n\r\f");
            tokens.nextToken(); // Gives us RTSP/1.0
            // Give us reply code
            replyCode = Integer.parseInt(tokens.nextToken());
            System.out.println("*** Reply Code: " + replyCode);
            // If the reply code is 200, then we are solid
            if (replyCode == 200) { // begin if
                // Cycle through the rest of the lines, delimited by \n
                // and print to the screen.  Also grab the relevant information
                // we need
                //for (String line = RTSPBufferedReader.readLine(); line != null;
                //    line = RTSPBufferedReader.readLine()) { // begin for

                // NEW: First we need to wait to see if we are ready to read
                String line;
                try {
                    while (!ctl.RTSPBufferedReader.ready()) {
                        continue;
                    }
                }
                catch(IOException e) {
                    System.out.println("Could not read from read buffer");
                    //e.printStackTrace();
                    return -1;
                }

                // If we are, while there is still data in the buffer...
                while (ctl.RTSPBufferedReader.ready()) { // begin for
                    line = ctl.RTSPBufferedReader.readLine();
                    if (line == null) // Also check to see if we have reached the end of the stream
                    {
                        break;
                    }

                    System.out.println(line);
                    // Tokenize
                    // Also includes semi-colons
                    tokens = new StringTokenizer(line, " \t\n\r\f;:");

                    // Now go through each token
                    while (tokens.hasMoreTokens()) { // begin while1
                        // Grab token
                        String part = tokens.nextToken();

                        // When we are using DESCRIBE - We are looking for the
                        // track numbers - This will allow us to request
                        // that particular stream of data so we can pipe it
                        // into our decoder buffers

                        // Usually looks like this:
                        // m=audio num RTP/AVP PT
                        // or
                        // m=video num RTP/AVP PT
                        // PT is the payload type or the type of media that is represented
                        // for the audio or video (i.e. audio: MP4, MP3, etc., video:
                        // H264, MPEG1, etc.)
                        if (part.equals("m=audio") && ctl.audioTrackID == -1) { // begin if2
                            // Skip next token
                            tokens.nextToken();

                            // Obtain the streaming protocol for the Audio
                            // Usually RTP/AVP
                            ctl.streamingProtocolAudio = new String(tokens.nextToken());

                            // Next token should contain our payload type
                            ctl.audioPT = Integer.parseInt(tokens.nextToken());
                            System.out.println("*** Audio PT: " + ctl.audioPT);

                            // Now advance each line until we hit "a=control"
                            while (true) { // begin while2
                                line = ctl.RTSPBufferedReader.readLine();
                                System.out.println(line);
                                if (line.indexOf("a=control") != -1 || line == null) {
                                    break;
                                }
                            } // end while2

                            if (line == null) { // begin if3
                                System.out.println("Could not find a=control String");
                                return replyCode;
                            } // end if3

                            // Once we hit "a=control", get the track number
                            StringTokenizer controlTokens = new StringTokenizer(line, " \t\n\r\f;:");
                            // Skip over a=control
                            controlTokens.nextToken();
                            // This should now contain our trackID
                            String trackID = controlTokens.nextToken();

                            // Look for the key trackID or stream and adjust accordingly
                            if (trackID.indexOf("trackID") != -1) {
                                ctl.audioTrackID = Integer.parseInt(trackID.substring(8, 9));
                                ctl.trackIDOrStream = true;
                                ctl.galbarmFlag = false;
                            }
                            ///// Fix thanks to galbarm
                            else if (trackID.indexOf("track") != -1) {
                                ctl.audioTrackID = Integer.parseInt(trackID.substring((trackID.indexOf("track")+5),trackID.length()));// 5, here is length of track i.e, "track".length()
                                ctl.trackIDOrStream = true;
                                ctl.galbarmFlag = true;
                            }
                            else if (trackID.indexOf("streamid") != -1) {
                                ctl.audioTrackID = Integer.parseInt(trackID.substring(9, 10));
                                ctl.trackIDOrStream = false;
                            } else if (trackID.indexOf("stream") != -1) {
                                ctl.audioTrackID = Integer.parseInt(trackID.substring(7, 8));
                                ctl.trackIDOrStream = false;
                            }

                            System.out.println("*** Audio Track: " + ctl.audioTrackID);
                            ctl.numberOfTracks++;

                            // Break out of this loop and continue reading the other lines
                            break;
                        } // end if2
                        else if (part.equals("m=video") && ctl.videoTrackID == -1) { // begin if2
                            // Skip next token
                            tokens.nextToken();

                            // Obtain the streaming protocol for the Audio
                            // Usually RTP/AVP
                            ctl.streamingProtocolVideo = new String(tokens.nextToken());

                            // Next token should contain our payload type
                            ctl.videoPT = Integer.parseInt(tokens.nextToken());
                            System.out.println("*** Video PT: " + ctl.videoPT);

                            // Now advance each line until we hit "a=control"
                            while (true) { // begin while2
                                line = ctl.RTSPBufferedReader.readLine();
                                System.out.println(line);
                                if (line.indexOf("a=control") != -1 || line == null) {
                                    break;
                                }
                            } // end while2

                            if (line == null) { // begin if3
                                System.out.println("Could not find a=control String");
                                return replyCode;
                            } // end if3

                            // Once we hit "a=control", get the track number
//                            StringTokenizer controlTokens = new StringTokenizer(line, " \t\n\r\f;:");
//                            // Skip over a=control
//                            controlTokens.nextToken();
//                            // This should now contain our trackID
//                            String trackID = controlTokens.nextToken();
                            String trackID = line;

                            // Look for the key trackID or stream and adjust accordingly
                            if (trackID.indexOf("trackID") != -1) {
                                ctl.videoTrackID = Integer.parseInt(trackID.substring((trackID.indexOf("trackID")+8),trackID.length())); // Integer.parseInt(trackID.substring(8, 9));
                                ctl.galbarmFlag = false;
                                ctl.trackIDOrStream = true;
                            }
                            ///// Fix thanks to galbarm
                            else if (trackID.indexOf("track") != -1) {
                                ctl.videoTrackID = Integer.parseInt(trackID.substring((trackID.indexOf("track")+5),trackID.length()));// 5, here is length of track i.e, "track".length()
                                ctl.galbarmFlag = true;
                                ctl.trackIDOrStream = true;
                            }
                            else if (trackID.indexOf("streamid") != -1) {
                                ctl.videoTrackID = Integer.parseInt(trackID.substring(trackID.indexOf("streamid") + 9));
                                ctl.trackIDOrStream = false;
                            } else if (trackID.indexOf("stream") != -1) {
                                ctl.videoTrackID = Integer.parseInt(trackID.substring(7, 8));
                                ctl.trackIDOrStream = false;
                            }

                            System.out.println("*** Video Track: " + ctl.videoTrackID);
                            ctl.numberOfTracks++;

                            // Break out of this loop and continue reading other lines
                            break;
                        } // end if2

                        // Extract the Session ID for subsequent setups
                        else if (part.equals("Session") && ctl.RTSPSessionID == null) { // begin if2
                            ctl.RTSPSessionID = tokens.nextToken();
                            System.out.println("*** Session ID: " + ctl.RTSPSessionID);
                            // Break out of this loop and continue reading other lines
                            break;
                        } // end if2
                    } // end while1
                } // end for
            } // end if
        } catch (IOException e) {
            System.out.println("Could not read in string from buffer");
            e.printStackTrace();
        }
        System.out.println("process finish!");
        return replyCode;
    }
}
